package com.gaojiawei.multiThread04_StopThreadMethod;

import org.junit.Test;

/**
 * stop线程的几种方式
 * 1.stop方法不用
 * 2.使用共享变量
 * 3.使用interrupt方式
 * 4.打断waiting和timewaiting状态的线程
 */
public class StopThread {

    private volatile boolean flag = true;


    /**
     * stop方法
     */
    @Test
    public void testStop(){
        Thread thread = new Thread(() -> {
            while (true) {

            }
        });
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.stop();
        System.out.println(thread.getState());

    }

    /**
     * 使用共享变量的方式
     * @throws InterruptedException
     */
    @Test
    public void testShare() throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (flag) {

            }
            System.out.println("线程停止");
        });

        thread.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        flag = false;
        Thread.sleep(10000);
    }

    /**
     * 使用interrupt方法
     */
    @Test
    public void testInterrupt() throws InterruptedException {
        //线程interrupt标记为默认为false
        System.out.println(Thread.currentThread().isInterrupted());
        //修改线程interrupt的标记为为true
        Thread.currentThread().interrupt();
        //再次查看
        System.out.println(Thread.currentThread().isInterrupted());
        //返回当前线程并归位false
        System.out.println( Thread.interrupted());
        System.out.println(Thread.interrupted());

        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {

            }
            System.out.println("线程终止");
        });

        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
        Thread.sleep(10000);


    }


    /**
     * 打断waiting和timewaiting状态的线程
     */
    @Test
    public void testStopWaitingandTimeWaiting() throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("线程终止");
                    return;
                }
            }
        });

        thread.start();

        Thread.sleep(500);

        thread.interrupt();
    }

}
